<script type="text/javascript">
<!--{literal}
$(document).ready
(
    function()
    {
	var service_qs = '';

	$('table#detail-grid')
	    .jqGrid
	    ({
		datatype:	'json',
		pager:		'detail-grid-pager',
		rowNum:		100,
		colNames:	['ID','Номер','Назначение','Продолжительность','Стоимость',"Дата",'Направление'],
		colModel:
		[
		    {name:'ID',width:100,hidden:true},
		    {name:'phone_number',width:120},
		    {name:'phone_dest',width:120},
		    {name:'duration',width:90},
		    {name:'cost',width:120},
		    {name:'date',width:220},
		    {name:'direction',width:250}
		]
	    });

	function resizeGrid(selector,w,h)
	{
	    $(selector)
		.setGridWidth(w)
		.setGridHeight(h)
		.trigger('resize');
	}

	$('div.dialog#detail').dialog
	(
	    'option',
	    {
		title:	'Формирование детализации',
		resizeStop:	function(e,ui) { resizeGrid('table#detail-grid',ui.size['width']-30,ui.size['height']-120); },
//		open:		function() { $('input#detail-grid').blur().blur(function(){$('input#detail-grid').datepicker('hide');}); }
		height:	400,
		width:	800
	    }
	);

	resizeGrid('table#detail-grid',770,280);

	$('input#detail-button').click
	(
	    function()
	    {
		var service_id = new Array;
		service_qs = '';

		$('input.service-item:checked').each(function(){service_id.push($(this).val());});

		for(i=0;i<service_id.length;i++){service_qs+='&service_id[]='+service_id[i];};

		if ( service_id.length>0 )
		{
		    $('table#detail-grid')
			.setGridParam({ url: 'detail.php?'+service_qs })
			.trigger('reloadGrid');

		    $('div.dialog#detail').dialog('open');
		}
	    }
	);

	$('input:button#set-date').click
	(
	    function()
	    {
		var date_start	= '&date_start='+$('input#detail-start').val();
		var date_stop	= '&date_stop='+$('input#detail-end').val();

		$('table#detail-grid')
		    .setGridParam({ url: 'detail.php?'+service_qs+date_start+date_stop })
		    .trigger('reloadGrid');
	    }
	);

	$('input:button#download-csv').click
	(
	    function()
	    {
		var date_start	= '&date_start='+$('input#detail-start').val();
		var date_stop	= '&date_stop='+$('input#detail-end').val();

		window.location.href = 'detail.php?csv=yes&in_win=yes'+service_qs+date_start+date_stop;
	    }
	);

	$('input:button#invoice-button').click
	(
	    function()
	    {
		var service_id = new Array;

		$('input.service-item').each(function(){if($(this).attr('checked')){service_id.push($(this).val());}});

		if ( service_id.length>0 )
		{
		    $('div#invoice-create')
			.dialog
			(
			    'option',
			    {
				title:	'Формирование счета',
				resizable:	false,
				buttons:
				{
				    'OK':	function()
						{
						    $.getJSON
						    (
							'invoice-create.php',
							{
							    date:	$('input:text#invoice-create-date').val(),
							    account_id:	$('input:hidden#account-id').val(),
							    service_id:	service_id
							},
							function(json)
							{
							    if ( json['r']=='OK' )
							    {
								if ( json['count']>0 )
								{
								    alert('Задание на формирование счета поставлено в очередь');
								    $('div#invoice-create').dialog('close');
								}
								else
								{
								    alert('Необработанное исключение, обратитесь к разработчику');
								}
							    }
							}
						    );
						}
				}
			    }
			)
			.dialog('open');
		}
		else
		{
		    alert('Не выбрано ни одной услуги!');
		}
	    }
	);
    }
);
{/literal}-->
</script>

<div class="dialog" id="detail">
    <table id="detail-grid"></table>
    <div id="detail-grid-pager"></div>
    <center>Период с <input type="text" class="date" id="detail-start"/> по <input type="text" class="date" id="detail-end"/>&nbsp;<input type="button" id="set-date" value="&rarr;"/>&nbsp;<input type="button" id="download-csv" value="Скачать CSV"/></center>
</div>

<div class="dialog" id="invoice-create">
    Дата: <input type="text" class="date" id="invoice-create-date"/>
</div>

<!-- Таблица списка услуг -->
<table id="service" width="95%" class="ui-widget" rules="all" cellspacing="0">
    <thead class="ui-widget-header">
	<tr>
	    <th rowspan="2">&nbsp;</th>
	    <th rowspan="2">#</th>
	    <th rowspan="2">Услуга</th>
	    <th rowspan="2">Кол-во</th>
	    <th rowspan="2">Исполнитель</th>
	    <th rowspan="2">Договор</th>
	    <th rowspan="2">Стоимость</th>
	    <th rowspan="2">Ежемесячная</th>
	    <th colspan="2">Период действия</th>
	    <th rowspan="2">Номер</th>
	    <th rowspan="2">Тариф</th>
	    <th rowspan="2">Начисления</th>
	   	<th rowspan="2">Статус</th>
{*
	    <th rowspan="2">Начисления<br/><small>себестоимость</small></th>
*}
	    <th rowspan="2">&nbsp;</th>
	</tr>
	<tr>
	    <th>Начало</th>
	    <th>Конец</th>
	</tr>
    </thead>
    <tbody>
    {foreach from=$services item=service name=service}
	<tr class="data-row{if $service.completed==1} ui-state-disabled{/if}" {if $service.completed==1 && $is_opera==TRUE}style="background-color: #ccc;"{/if}>
	    <td align="center"><span style="display: none;">{$service.srv_id}</span><input type="checkbox" class="service-item" id="service-{$service.srv_id}" value="{$service.srv_id}"/></td>
	    <td>{$smarty.foreach.service.iteration}</td>
	    <td><label for="service-{$service.srv_id}">{$service.service_name}</label></td>
	    <td align="center">{$service.quantity}</td>
	    <td>{$service.executive_name|sslash}</td>
	    <td>{$service.contract_number}</td>
	    <td align="right" style="padding-right: 2em;">{$service.cost|string_format:'%0.2f'}</td>
	    <td align="center"><img src="images/icons/{if $service.monthly==1}tick_16.png{else}block_16.png{/if}"/></td>
	    <td align="center">{if $service.start_date>0}{$service.start_date|date_format:'%d.%m.%Y'}{else}&mdash;{/if}</td>
	    <td align="center">{if $service.stop_date>0}{$service.stop_date|date_format:'%d.%m.%Y'}{else}&mdash;{/if}</td>

	    {* Проверяем, является ли услуга телефонией или IP телефонией. В нашем случае это услуга (class) имеет voice или voip *}
	    {if ($service.class=='voice' || $service.class=='voip')}
		    <td align="center">{$service.phone_number}</td>
		    <td align="center">{$service.rate_name}</td>
		    <td align="center">{$service.last_cost|default:'&mdash;'}</td>
	    {else}
	    	<td colspan="3" align="center">&mdash;</td>
	    {/if}
	    {if $service.class=='voip'}
	    	{if $service.status=='online'}
	    		<td align="center" bgcolor="#3CB371" title="online">{$service.contact_ip}</td>
	    	{/if}
	    	{if $service.status=='offline'}
	    		<td align="center" bgcolor="#CD5C5C" title="offline">{$service.contact_ip}</td>
	    	{/if}
	    	{if $service.status=='billing_block'}
	    		<td align="center" bgcolor="#EE82EE" title="блокировка биллинга">{$service.contact_ip}</td>
	    	{/if}
	    	{if $service.status=='administrative_block'}
	    		<td align="center" bgcolor="#FFFF00" title="административная блокировка">{$service.contact_ip}</td>
	    	{/if}
	    	{if $service.status==NULL}
	    		<td align="center" title="неопределено">&mdash;</td>
	    	{/if}
	    {else}
	    	<td align="center">&mdash;</td>
	    {/if}
	    <td align="center"><a href="service-delete.php?id={$service.srv_id}"><img src="images/icons/delete_16.png" border="0"/></a></td>
	</tr>
	
    {foreachelse}
	<tr><td colspan="13" align="center"><i>нет услуг</i></td></tr>
    {/foreach}
    </tbody>
</table>
<br/><br/>
<a href="javascript:void(0)" id="service-add"><img src="images/icons/plus_16.png" border="0"/>&nbsp;Добавить услугу</a>
<br/><br/>
<input type="button" value="Детализация" class="button" id="detail-button"/>
<input type="button" value="Выставить счет" class="button" id="invoice-button"/>
